local RSNG = RSNG
local C = RSNG.Classes

local Pool = AceOO.Class()

function Pool.prototype:init(class)
	self.class = class
	self.content = {}
	self.offset = 0
end

function Pool.prototype:New()
	local offset, content = self.offset + 1, self.content
	local object
	if offset <= #content then
		object = content[offset]
	else
		object = self.class:new()
		object:Create(RSNG:GetParentFrame())
		object:GetFrame():Show()
		content[offset] = object
	end
	self.offset = offset
	return object
end

function Pool.prototype:Release(object)
	local offset, content = self.offset, self.content
	local index
	for i = offset, 1, -1 do
		if content[i] == object then
			index = i
			break
		end
	end
	assert(index)
	if index ~= offset then
		content[index], content[offset] = content[offset], content[index]
	end
	self.offset = offset - 1
	object:SetInfo()
	object:GetFrame():Hide()
end

function Pool.prototype:Clear()
	local content = self.content
	for i = self.offset, 1, -1 do
		content[i]:SetInfo()
		content[i]:GetFrame():Hide()
	end
	self.offset = 0
end

RSNG.Pools = setmetatable({}, {
	__index = function (self, name)
		local class = RSNG.Registries.UI:Get(name)
		if not class then return end
		local pool = Pool:new(class)
		self[name] = pool
		return pool
	end
})
